package com.mysoft.gfyx.marketdevelop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Joiner;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.context.info.ContextInfo;
import com.mysoft.framework.modeling.dto.*;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.common.util.MyStringUtil;
import com.mysoft.gfyx.common.ycg.YcgFileService;
import com.mysoft.gfyx.marketdevelop.controller.dto.advancesearch.*;
import com.mysoft.gfyx.marketdevelop.dao.*;
import com.mysoft.gfyx.marketdevelop.dao.entity.*;
import com.mysoft.gfyx.marketdevelop.mip.dto.*;
import com.mysoft.gfyx.marketdevelop.mip.dto.TjTag.TagFilter;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteCustomerService;
import com.mysoft.gfyx.marketdevelop.service.*;
import com.mysoft.gfyx.marketdevelop.service.dto.AdvanceSearchUserSavedDetailDto;
import com.mysoft.gfyx.marketdevelop.service.dto.AdvanceSearchUserSavedDto;
import com.mysoft.gfyx.marketdevelop.service.dto.ProvinceAndCityDto;
import com.mysoft.gfyx.marketdevelop.service.dto.TagDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service
public class AdvanceSearchServiceImp extends AppService implements AdvanceSearchService {

    @Resource
    AdvanceSearchFieldGroupDao advanceSearchFieldGroupDao;

    @Resource
    AdvanceSearchFieldDao advanceSearchFieldDao;

    @Resource
    AdvanceSearchWidgetDao advanceSearchWidgetDao;

    @Resource
    DeveloperService developerService;

    @Resource
    AdvanceSearchUserSavedDao advanceSearchUserSavedDao;

    @Resource
    AdvanceSearchUserSavedDetailDao advanceSearchUserSavedDetailDao;

    @Resource
    ProvinceAndCityService provinceAndCityService;

    @Resource
    YcgFileService ycgFileService;

    @Resource
    ContextManager contextManager;

    @Resource
    CommonService commonService;

    @Resource
    LabelService labelService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Override
    //获取高级筛选字段组+字段元数据
    public AdvanceSearchFieldGroupDto getAdvanceSearchFieldGroup() {
        //获取所有组
        AdvanceSearchFieldGroupDto advanceSearchFieldGroupDto = new AdvanceSearchFieldGroupDto();
        QueryWrapper<AdvanceSearchFieldGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("Sort");
        List<AdvanceSearchFieldGroup> advanceSearchFieldGroups = advanceSearchFieldGroupDao.selectList(queryWrapper);
        List<GroupDto> groupDtoList = MappingUtil.getSimpleMapperFacade().mapAsList(advanceSearchFieldGroups, GroupDto.class);
        //设置所有组
        advanceSearchFieldGroupDto.setGroups(groupDtoList);

        //获取所有字段
        QueryWrapper<AdvanceSearchField> advanceSearchFieldQueryWrapper = new QueryWrapper<>();
        advanceSearchFieldQueryWrapper.orderByDesc("Sort");
        List<AdvanceSearchField> advanceSearchFieldList = advanceSearchFieldDao.selectList(advanceSearchFieldQueryWrapper);

        //获取所有组件
        List<AdvanceSearchWidget> advanceSearchWidgetList = advanceSearchWidgetDao.selectList(null);

        //获取所有标签
        ArrayList<TagDto> tagDtoArrayList = developerService.getAllTags();

        List<AdvanceSearchFieldDto> advanceSearchFieldDtoList = new ArrayList<>();
        JSONObject fieldValueOptions = new JSONObject();
        for (AdvanceSearchField advanceSearchField : advanceSearchFieldList) {
            AdvanceSearchFieldDto advanceSearchFieldDto = new AdvanceSearchFieldDto();
            advanceSearchFieldDto.setAdvanceSearchFieldGroupGUID(advanceSearchField.getAdvanceSearchFieldGroupGUID());
            advanceSearchFieldDto.setLabel(advanceSearchField.getLabel());
            advanceSearchFieldDto.setFieldName(advanceSearchField.getFieldName());
            advanceSearchFieldDto.setTableName(advanceSearchField.getTableName());
            ActionDto actionDto = new ActionDto();
            actionDto.setActionCode(JSONArray.parseArray(advanceSearchField.getActionCode()));
            actionDto.setOptions(JSONArray.parseArray(advanceSearchField.getActionOptions())); //todo options
            advanceSearchFieldDto.setAction(actionDto);
            JSONObject inputConfigJsonObject = JSON.parseObject(advanceSearchField.getConfig());
            for (AdvanceSearchWidget advanceSearchWidget : advanceSearchWidgetList) {
                if (advanceSearchField.getAdvanceSearchWidgetGUID().equals(advanceSearchWidget.getAdvanceSearchWidgetGUID())) {
                    inputConfigJsonObject.put("widgetCode", advanceSearchWidget.getWidgetCode());
                    inputConfigJsonObject.put("widgetName", advanceSearchWidget.getWidgetName());
                    break;
                }
            }
            advanceSearchFieldDto.setInputConfig(inputConfigJsonObject);
            advanceSearchFieldDtoList.add(advanceSearchFieldDto);
            if (advanceSearchField.getFieldValueOptions() != null && !advanceSearchField.getFieldValueOptions().equals("")) {
                fieldValueOptions.put(advanceSearchField.getTableName()+"_"+advanceSearchField.getFieldName(), JSONArray.parseArray(advanceSearchField.getFieldValueOptions()));
            }

            //标签类字段，暂时写死 todo
            String tagFieldsKey = advanceSearchField.getTableName() + "_" + advanceSearchField.getFieldName();
            if (AdvanceSearchService.tagFields.containsKey(tagFieldsKey)) {
                for(TagDto tagDto : tagDtoArrayList) {
                    //匹配到
                    if (tagDto.getTag_name_en().equals(AdvanceSearchService.tagFields.get(tagFieldsKey))) {
                        List<FieldValueOptionsDto> fieldValueOptionsDtoList = new ArrayList<>();
                        //对象转换
                        for (int k =0; k < tagDto.getValue_list().size(); k++) {
                            FieldValueOptionsDto fieldValueOptionsDto = new FieldValueOptionsDto();
                            fieldValueOptionsDto.setValue(tagDto.getValue_list().get(k).getTag_value_id());
                            fieldValueOptionsDto.setText(tagDto.getValue_list().get(k).getTag_value_name());
                            fieldValueOptionsDtoList.add(fieldValueOptionsDto);
                        }
                        //企业类型的枚举列表添加到公共字段值选项字段
                        fieldValueOptions.put(tagFieldsKey, fieldValueOptionsDtoList);
                    }
                }
            }
        }
        //设置所有字段
        advanceSearchFieldGroupDto.setFields(advanceSearchFieldDtoList);

        advanceSearchFieldGroupDto.setFieldValueOptions(fieldValueOptions);
        return advanceSearchFieldGroupDto;
    }

    @Override
    public BaseTjListDto searchCustomer(AdvanceSearchCustomerRequestDto advanceSearchCustomerRequestDto) {
        //供方saas高级筛选dto转换成数芯的dto
        GetDeveloperFilterDataRequestDto getDeveloperFilterDataRequestDto = this.toTjAdvanceSearchCustomerRequestDto(advanceSearchCustomerRequestDto);
        return developerService.getDeveloperDetailData(getDeveloperFilterDataRequestDto);
    }

    @Override
    //找商机
    public BaseTjListDto searchOpptyPurchase(AdvanceSearchCustomerRequestDto advanceSearchCustomerRequestDto) {
        //供方saas高级筛选dto转换成数芯的dto
        GetDeveloperFilterDataRequestDto getDeveloperFilterDataRequestDto = this.toTjAdvanceSearchOpptyPurchaseRequestDto(advanceSearchCustomerRequestDto);
        return developerService.searchOpptyPurchase(getDeveloperFilterDataRequestDto);
    }

    @Override
    public UUID saveAdvanceSearchTemplate(SaveAdvanceSearchTemplateRequestDto saveAdvanceSearchTemplateRequestDto) {
        ContextInfo contextInfo = contextManager.fetchContextInfo();
        UUID userId = contextInfo.getUserContext().getUserId();
        String userName = contextInfo.getUserContext().getUserName();
        QueryWrapper<AdvanceSearchUserSaved> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CreatedName", userName);
        queryWrapper.eq("TemplateName", saveAdvanceSearchTemplateRequestDto.getTemplateName());
        List<AdvanceSearchUserSaved> AdvanceSearchUserSavedList = advanceSearchUserSavedDao.selectList(queryWrapper);
        if (AdvanceSearchUserSavedList.size() > 0) {
            throw new BusinessLogicException("该筛选组名称已存在");
        }
        //转换对象
        AdvanceSearchUserSaved advanceSearchUserSaved = new AdvanceSearchUserSaved();
        advanceSearchUserSaved.setTemplateName(saveAdvanceSearchTemplateRequestDto.getTemplateName());
        advanceSearchUserSaved.setIsEnable(1);
//        advanceSearchUserSaved.setSort(1); todo 排序怎么计算？
        advanceSearchUserSaved.setUseFrom(0);
        advanceSearchUserSaved.setCreatedName(userName);
        advanceSearchUserSaved.setCreatedGUID(userId);
        advanceSearchUserSaved.setCreatedTime(new Date());
        //插入数据表 todo 事务
        advanceSearchUserSavedDao.insert(advanceSearchUserSaved);
        System.out.println("advanceSearchUserSaved=" + advanceSearchUserSaved);
        //插入模板字段明细表
        List<AdvanceSearchUserSavedDetail> advanceSearchUserSavedDetailList = new ArrayList<>();
        AdvanceSearchUserSavedDetail advanceSearchUserSavedDetailOne = new AdvanceSearchUserSavedDetail();
        advanceSearchUserSavedDetailOne.setFieldName("relative");
        advanceSearchUserSavedDetailOne.setActionCode("eq");
        advanceSearchUserSavedDetailOne.setActionValue("["+saveAdvanceSearchTemplateRequestDto.getRelative()+"]");
        advanceSearchUserSavedDetailOne.setAdvanceSearchUserSavedGUID(advanceSearchUserSaved.getAdvanceSearchUserSavedGUID());
        advanceSearchUserSavedDetailOne.setSort(0);
        advanceSearchUserSavedDetailOne.setCreatedGUID(userId);
        advanceSearchUserSavedDetailOne.setCreatedName(userName);
        advanceSearchUserSavedDetailOne.setCreatedTime(new Date());
        advanceSearchUserSavedDetailList.add(advanceSearchUserSavedDetailOne);
        int i = 1;
        for (FiltersDto filtersDto : saveAdvanceSearchTemplateRequestDto.getFilters()) {
            AdvanceSearchUserSavedDetail advanceSearchUserSavedDetail = new AdvanceSearchUserSavedDetail();
            advanceSearchUserSavedDetail.setFieldName(filtersDto.getAttributeName());
            advanceSearchUserSavedDetail.setActionCode(filtersDto.getActionCode());
            advanceSearchUserSavedDetail.setTableName(filtersDto.getTableName());
            advanceSearchUserSavedDetail.setActionValue(JSON.toJSONString(filtersDto.getActionValue()));

            advanceSearchUserSavedDetail.setAdvanceSearchUserSavedGUID(advanceSearchUserSaved.getAdvanceSearchUserSavedGUID());
            advanceSearchUserSavedDetail.setSort(i);
            advanceSearchUserSavedDetail.setCreatedGUID(userId);
            advanceSearchUserSavedDetail.setCreatedName(userName);
            advanceSearchUserSavedDetail.setCreatedTime(new Date());
            advanceSearchUserSavedDetailList.add(advanceSearchUserSavedDetail);
            i++;
        }
        System.out.println("advanceSearchUserSavedDetailList=================" + advanceSearchUserSavedDetailList.toString());
        advanceSearchUserSavedDetailDao.insertBatch(advanceSearchUserSavedDetailList);
        return advanceSearchUserSaved.getAdvanceSearchUserSavedGUID();
    }

    @Override
    public boolean addAdvanceSearchTemplateUseCount(AdvanceSearchUserSavedDto advanceSearchUserSavedDto) {
        AdvanceSearchUserSaved advanceSearchUserSaved = MappingUtil.getSimpleMapperFacade().map(advanceSearchUserSavedDto, AdvanceSearchUserSaved.class);
        advanceSearchUserSaved.setUseCount(advanceSearchUserSaved.getUseCount()+1);
        advanceSearchUserSavedDao.updateById(advanceSearchUserSaved);
        return true;
    }

    @Override
    public List<AdvanceSearchUserSavedDto> getSavedAdvanceSearchTemplate() {
        ContextInfo contextInfo = contextManager.fetchContextInfo();
        UUID userId = contextInfo.getUserContext().getUserId();
        QueryWrapper<AdvanceSearchUserSaved> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("Sort");
        queryWrapper.orderByDesc("CreatedTime");
        queryWrapper.eq("CreatedGUID", userId);
        List<AdvanceSearchUserSaved> advanceSearchUserSavedList = advanceSearchUserSavedDao.selectList(queryWrapper);
        List<AdvanceSearchUserSavedDto> advanceSearchUserSavedDtoList = MappingUtil.getSimpleMapperFacade().mapAsList(advanceSearchUserSavedList, AdvanceSearchUserSavedDto.class);

        return advanceSearchUserSavedDtoList;
    }

    @Override
    public AdvanceSearchUserSavedDto getSavedAdvanceSearchTemplateById(UUID advanceSearchUserSavedGUID) {
        AdvanceSearchUserSaved advanceSearchUserSaved = advanceSearchUserSavedDao.selectById(advanceSearchUserSavedGUID);
        AdvanceSearchUserSavedDto advanceSearchUserSavedDto = MappingUtil.getSimpleMapperFacade().map(advanceSearchUserSaved, AdvanceSearchUserSavedDto.class);
        return advanceSearchUserSavedDto;
    }

    @Override
    public boolean delSavedAdvanceSearchTemplate(UUID advanceSearchUserSavedGUID) {
        advanceSearchUserSavedDao.deleteById(advanceSearchUserSavedGUID);
        QueryWrapper<AdvanceSearchUserSavedDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("AdvanceSearchUserSavedGUID", advanceSearchUserSavedGUID);
        List<AdvanceSearchUserSavedDetailDto> advanceSearchUserSavedDetailDtoList = this.getSavedAdvanceSearchTemplateDetail(advanceSearchUserSavedGUID);
        List<UUID> idList = new ArrayList<UUID>();
        for (AdvanceSearchUserSavedDetailDto advanceSearchUserSavedDetailDto : advanceSearchUserSavedDetailDtoList) {
            idList.add(advanceSearchUserSavedDetailDto.getAdvanceSearchUserSavedDetailGUID());
        }
        advanceSearchUserSavedDetailDao.deleteBatchIds(idList);
        return true;
    }

    @Override
    public FieldsSetting loadSearchCustomerFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("organizing_code");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_developer";
        fieldsSetting.getFields().add(new DataApiField(SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_nameHL", groupName, "高亮客户名称", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("legal_name", groupName, "企业法人", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("regist_capi", groupName, "注册资本", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("establish_date", groupName, "成立日期", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("address", groupName, "详细地址", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("nearly_a_year_taken_land", groupName, "近一年拿地", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("nearly_a_year_open_project", groupName, "近一年开盘", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("nearly_a_year_purchase_demand", groupName, "近一年需求", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("nearly_a_year_cooperation_enterprise", groupName, "近一年合作单位", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("cooperation_enterprise", groupName, "合作单位", FieldType.Decimal));
        fieldsSetting.getFields().add(new DataApiField("tags", groupName, "标签", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("developer_logo", groupName, "企业logo", FieldType.Picture));
        fieldsSetting.getFields().add(new DataApiField("top_company_summary", groupName, "顶级公司", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("has_added", groupName, "是否已添加过客户", FieldType.Int));
        fieldsSetting.getFields().add(new DataApiField("province_code", groupName, "省份编码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("province", groupName, "所属省份", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city", groupName, "所属城市", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("city_code", groupName, "城市编码", FieldType.String));
        // 返回
        return fieldsSetting;
    }

    @Override
    public FieldsSetting loadSearchOpptyPurchaseFields() {
        //硬编码的获取字段逻辑
        FieldsSetting fieldsSetting = new FieldsSetting();
        fieldsSetting.setIdField("uid");
        fieldsSetting.setFields(new ArrayList<>());
        String groupName = "developer_search_oppo";
        fieldsSetting.getFields().add(new DataApiField("uid", groupName, "UID", FieldType.String));
        //用来跳转采购详情页面
        fieldsSetting.getFields().add(new DataApiField("id", groupName, "id", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField(SearchDeveloperRequestDto.FILTER_DEVELOPER_NAME, groupName, "招标单位", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("organizing_code", groupName, "社会统一信用代码", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("title", groupName, "标题", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("publish_time", groupName, "发布时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("end_time", groupName, "截止时间", FieldType.String));
        fieldsSetting.getFields().add(new DataApiField("tags", groupName, "标签", FieldType.String));

        // 返回
        return fieldsSetting;
    }

    @Override
    public ListDataResult loadSearchOpptyPurchaseData(LoadDataParams options) {
        AdvanceSearchCustomerRequestDto advanceSearchOpptyPurchaseRequestDto = JSON.parseObject(JSON.toJSONString(options.getOptions().getContext()), AdvanceSearchCustomerRequestDto.class);
        if (advanceSearchOpptyPurchaseRequestDto == null) {
            advanceSearchOpptyPurchaseRequestDto = new AdvanceSearchCustomerRequestDto();
        }
        advanceSearchOpptyPurchaseRequestDto.setPage_size(options.getPageSize());
        int page = 0;
        if (options.getPageIndex() == 0) {
            page = 0;
        } else {
            page = options.getPageIndex()+1;
        }
        advanceSearchOpptyPurchaseRequestDto.setPage(page);

        System.out.println("options=========" + options.getOptions().getContext());
        System.out.println("advanceSearchOpptyPurchaseRequestDto=========" + advanceSearchOpptyPurchaseRequestDto);
//        // 分页
//        Page<Room> page = ExtensionLoadDataHelper.getPage(options);
//        QueryWrapper<Room> query = ExtensionLoadDataHelper.warp(Room.class, options);
//        // 查询
//        IPage<Room> roomPage = roomDao.selectPage(page, query);
        ListDataResult result = new ListDataResult();
        BaseTjListDto data = this.searchOpptyPurchase(advanceSearchOpptyPurchaseRequestDto);
//        result.setData(MappingUtil.getSimpleMapperFacade().mapAsList(roomPage.getRecords(), RoomDto.class));
        ArrayList<Object> arrayList = new ArrayList<>();
        ArrayList<BaseTjListItemDto> baseTjListItemDtoArrayList = data.getList();
        if (baseTjListItemDtoArrayList == null) {
            result.setData(arrayList);
            result.setTotal(0);
        } else {
            data.getList().forEach(r -> {
                Map<String, Object> map = r.getItem();
                map.put("tags", "");
                List<String> tagList = new ArrayList<>();
                tagList.add((String) map.get("data_source"));
                try {
                    Date publishTimeDate = commonService.dateTimeStringToDate((String) map.get("publish_time"), null);
                    Date endTimeDate = commonService.dateTimeStringToDate((String) map.get("end_time"), null);
                    Date nowDate = new Date();
                    if (nowDate.after(publishTimeDate) && nowDate.before(endTimeDate)) {
                        tagList.add("报名中");
                    } else {
                        tagList.add("已截止");
                    }
                } catch (Exception e) {
//                    throw new BusinessLogicException(e.getMessage());
                }
                List<String> biddingServiceCategoryList = new ArrayList<>();
                biddingServiceCategoryList = Arrays.asList(((String) map.get("bidding_service_category")).split(","));
                tagList.addAll(biddingServiceCategoryList);
                List<String> nullList = new ArrayList<String>();
                nullList.add(null);
                nullList.add("");
                tagList.removeAll(nullList);
                List<String> tagsDistinctArr = tagList.stream().distinct().collect(Collectors.toList());
                map.put("tags", Joiner.on(",").join(tagsDistinctArr));
                if (map.get("publish_time").equals("")) {
                    map.put("publish_time", "--");
                } else {
                    try {
                        Date date = commonService.dateTimeStringToDate((String) map.get("publish_time"), null);
                        map.put("publish_time", commonService.dateToDateString(date));
                    } catch (ParseException e) {
                        map.put("publish_time", "--");
                    }
                }
                if (map.get("end_time").equals("")) {
                    map.put("end_time", "--");
                } else {
                    try {
                        Date date = commonService.dateTimeStringToDate((String) map.get("end_time"), null);
                        map.put("end_time", commonService.dateToDateString(date));
                    } catch (ParseException e) {
                        map.put("end_time", "--");
                    }
                }
//                if (r.getTag_infos() != null) {
//                    List<String> tagsArr = new ArrayList<>();
//                    for (int i = 0; i < r.getTag_infos().size(); i++) {
//                        tagsArr.add((String) r.getTag_infos().get(i).get("tag_value"));
//                    }
//                    map.put("tags", Joiner.on(",").join(tagsArr));
//                }
                arrayList.add(map);
            });
            result.setData(arrayList);
            result.setTotal(data.getTotal());
        }
        return result;
    }

    @Override
    public ListDataResult loadSearchCustomerData(LoadDataParams options) {
        AdvanceSearchCustomerRequestDto advanceSearchCustomerRequestDto = JSON.parseObject(JSON.toJSONString(options.getOptions().getContext()), AdvanceSearchCustomerRequestDto.class);
        if (advanceSearchCustomerRequestDto == null) {
            advanceSearchCustomerRequestDto = new AdvanceSearchCustomerRequestDto();
        }
        advanceSearchCustomerRequestDto.setPage_size(options.getPageSize());
        advanceSearchCustomerRequestDto.setPage(options.getPageIndex()+1);
        System.out.println("options=========" + options.getOptions().getContext());
        System.out.println("searchCustomerRequest=========" + advanceSearchCustomerRequestDto);
//        // 分页
//        Page<Room> page = ExtensionLoadDataHelper.getPage(options);
//        QueryWrapper<Room> query = ExtensionLoadDataHelper.warp(Room.class, options);
//        // 查询
//        IPage<Room> roomPage = roomDao.selectPage(page, query);
        ListDataResult result = new ListDataResult();
        BaseTjListDto data = this.searchCustomer(advanceSearchCustomerRequestDto);
//        result.setData(MappingUtil.getSimpleMapperFacade().mapAsList(roomPage.getRecords(), RoomDto.class));
        ArrayList<Object> arrayList = new ArrayList<>();
        ArrayList<BaseTjListItemDto> baseTjListItemDtoArrayList = data.getList();
        if (baseTjListItemDtoArrayList == null) {
            result.setData(arrayList);
            result.setTotal(0);
        } else {
            //页面显示的标签
            ArrayList<String> pageShowTagIds = new ArrayList<>();
            //获取数芯所有标签
            ArrayList<TagDto> tagDtoArrayList = developerService.getAllTags();
            //经营状态标签id
            AtomicReference<String> business_status_label_id = new AtomicReference<>("");
            //企业类型标签id
            AtomicReference<String> company_type_label_tag_id = new AtomicReference<>("");
            tagDtoArrayList.forEach(t -> {
                if (t.getTag_name_en().equals("company_type_label") || t.getTag_name_en().equals("business_status_label")) {
                    pageShowTagIds.add(t.getTag_id());
                    if (t.getTag_name_en().equals("business_status_label")) {
                        business_status_label_id.set(t.getTag_id());
                    }
                    if (t.getTag_name_en().equals("company_type_label")) {
                        company_type_label_tag_id.set(t.getTag_id());
                    }
                }
            });

            List<String> organizingCodeList = new ArrayList<>();
            data.getList().forEach(r -> {
                Map<String, Object> map = r.getItem();
                String organizingCode = (String) map.get("organizing_code");
                if (organizingCode != null && !organizingCode.equals("")) {
                    organizingCodeList.add(organizingCode);
                }
            });
            //todo page
            BaseTjListDto metricsListDto = developerService.getMetricsList(organizingCodeList,1,200);

            Set<String> haveAdded = remoteCustomerService.isAdded(organizingCodeList);

            data.getList().forEach(r -> {
                Map<String, Object> map = r.getItem();
                //todo
                map.put("nearly_a_year_taken_land", "0");
                map.put("nearly_a_year_open_project", "0");
                map.put("nearly_a_year_purchase_demand", "0");
                map.put("nearly_a_year_cooperation_enterprise", "0");
                map.put("cooperation_enterprise", "0");
//                ArrayList<Map<String, Object>> tags = new ArrayList<>();
                map.put("tags", "");
                map.put("developer_logo", ycgFileService.getEnterpriseLogo(map.get("developer_id").toString(), map.get("developer_logo").toString()));
                //注册资本
                if (map.get("regist_capi").equals("")) {
                    map.put("regist_capi", "--");
                } else {
                    map.put("regist_capi", map.get("regist_capi") + "万元");
                }
                if (map.get("establish_date").equals("")) {
                    map.put("establish_date", "--");
                } else {
                    try {
                        Date date = commonService.dateTimeStringToDate((String) map.get("establish_date"), null);
                        map.put("establish_date", commonService.dateToDateString(date));
                    } catch (ParseException e) {
                        map.put("establish_date", "--");
                    }
                }
                if (metricsListDto != null && metricsListDto.getList() != null) {
                    for (BaseTjListItemDto metricItem : metricsListDto.getList()) {
                        if (metricItem.getItem().get("organizing_code").toString().equals(map.get("organizing_code").toString())) {
                            map.put("nearly_a_year_taken_land", this.removeDecimalPoint((String) metricItem.getItem().get("nearly_a_year_taken_land")));
                            map.put("nearly_a_year_open_project", this.removeDecimalPoint((String) metricItem.getItem().get("nearly_a_year_open_project")));
                            map.put("nearly_a_year_purchase_demand", this.removeDecimalPoint((String) metricItem.getItem().get("nearly_a_year_purchase_demand")));
                            map.put("nearly_a_year_cooperation_enterprise", this.removeDecimalPoint((String) metricItem.getItem().get("nearly_a_year_cooperation_enterprise")));
                            map.put("cooperation_enterprise", this.removeDecimalPoint((String) metricItem.getItem().get("cooperation_enterprise")));
                        }
                    }
                }
                // 顶级公司
                String topCompanyType = labelService.extractAndDeleteTagValueNameWithTagName(r.getTag_infos(), DeveloperService.TjEntity.Developer, LabelService.LABEL_TOP_COMPANY_TYPE);
                if (map.get("top_organizing_code") != null && (! "".equals(map.get("top_organizing_code"))) ) {
                    if (topCompanyType.equals("")) {
                        map.put("top_company_summary", map.get("top_developer_name"));
                    } else {
                        map.put("top_company_summary", map.get("top_developer_name") + "【" + topCompanyType +  "】");
                    }
                } else {
                    map.put("top_company_summary", "NULL");
                }
                if (r.getTag_infos() != null) {
                    List<String> tagsArr = new ArrayList<>();

                    List<String> newTagsArr = new ArrayList<>();
                    for (Map<String, Object> tagInfo : r.getTag_infos()) {
                        String tagsString = tagInfo.get("tag_value").toString();
                        newTagsArr.add(tagsString);
                    }
                    if (newTagsArr.contains("上市企业")) {
                        newTagsArr.removeIf(next -> next.equals("上市企业"));
                        newTagsArr.add("上市企业");
                    }
                    map.put("tags", Joiner.on(",").join(newTagsArr));
                }
                //拼接逗号分割的标签
//                map.put("uuid", UUID.randomUUID().toString());

                // 是否添加过
                int hasAdded = haveAdded.contains(map.get("organizing_code").toString()) ? 1 : 0;
                map.put("has_added", hasAdded);

                arrayList.add(map);
            });
            result.setData(arrayList);
            result.setTotal(data.getTotal());
        }
        return result;
    }

    //去除字符串小数点
    private String removeDecimalPoint (String str) {
        int i = str.indexOf(".");//首先获取字符的位置
        if (i != -1) {
            String newStr = str.substring(0,i);//再对字符串进行截取，获得想要得到的字符串
            return newStr;
        }
        if (str.equals("")) {
            return "0";
        }
        return str;
    }
    @Override
    public List<AdvanceSearchUserSavedDetailDto> getSavedAdvanceSearchTemplateDetail(UUID advanceSearchUserSavedGUID) {
        ContextInfo contextInfo = contextManager.fetchContextInfo();
        UUID userId = contextInfo.getUserContext().getUserId();
        QueryWrapper<AdvanceSearchUserSavedDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("Sort");
        queryWrapper.eq("AdvanceSearchUserSavedGUID", advanceSearchUserSavedGUID);
        List<AdvanceSearchUserSavedDetail> advanceSearchUserSavedDetailList = advanceSearchUserSavedDetailDao.selectList(queryWrapper);
        List<AdvanceSearchUserSavedDetailDto> advanceSearchUserSavedDetailDtoList = MappingUtil.getSimpleMapperFacade().mapAsList(advanceSearchUserSavedDetailList, AdvanceSearchUserSavedDetailDto.class);
        return advanceSearchUserSavedDetailDtoList;
    }

    //供方saas高级筛选找客户dto转换成数芯的dto
    public GetDeveloperFilterDataRequestDto toTjAdvanceSearchCustomerRequestDto(AdvanceSearchCustomerRequestDto advanceSearchCustomerRequestDto) {
        //供方saas高级筛选dto转换成数芯的dto
        GetDeveloperFilterDataRequestDto getDeveloperFilterDataRequestDto = new GetDeveloperFilterDataRequestDto();
        if (advanceSearchCustomerRequestDto.getFilters() == null) {
            List<FiltersDto> filtersDtoList = new ArrayList<>();
            advanceSearchCustomerRequestDto.setFilters(filtersDtoList);
        }
        ArrayList<BaseTjFilterDto> baseTjFilterDtoList = assemTjFilters(advanceSearchCustomerRequestDto, getDeveloperFilterDataRequestDto);
        getDeveloperFilterDataRequestDto.setFilters(baseTjFilterDtoList);
        getDeveloperFilterDataRequestDto.setPage(advanceSearchCustomerRequestDto.getPage());
        getDeveloperFilterDataRequestDto.setPage_size(advanceSearchCustomerRequestDto.getPage_size());
        return getDeveloperFilterDataRequestDto;
    }

    //供方saas高级筛选找商机dto转换成数芯的dto
    public GetDeveloperFilterDataRequestDto toTjAdvanceSearchOpptyPurchaseRequestDto(AdvanceSearchCustomerRequestDto advanceSearchOpptyPurchaseRequestDto) {
        GetDeveloperFilterDataRequestDto getDeveloperFilterDataRequestDto = new GetDeveloperFilterDataRequestDto();
        if (advanceSearchOpptyPurchaseRequestDto.getFilters() == null) {
            List<FiltersDto> filtersDtoList = new ArrayList<>();
            advanceSearchOpptyPurchaseRequestDto.setFilters(filtersDtoList);
        }
        ArrayList<BaseTjFilterDto> baseTjFilterDtoList = assemTjFilters(advanceSearchOpptyPurchaseRequestDto, getDeveloperFilterDataRequestDto);
        getDeveloperFilterDataRequestDto.setFilters(baseTjFilterDtoList);
        getDeveloperFilterDataRequestDto.setDetail_table_name("dwd_ycg_kfs_purchase_demand_m");
        getDeveloperFilterDataRequestDto.setPage(advanceSearchOpptyPurchaseRequestDto.getPage());
        getDeveloperFilterDataRequestDto.setPage_size(advanceSearchOpptyPurchaseRequestDto.getPage_size());
        return getDeveloperFilterDataRequestDto;
    }

    /**
     * 拼装数芯需要的过滤条件
     * {
     *
     *     "relative": 1,
     *     "filters": [
     *         {
     *             "attributeName": "developer_name",
     *             "actionCode": 2,
     *             "actionValue": ["中国"],
     *             "tableName": "dim_ycg_common_developer_m"
     *         },
     *         {
     *             "attributeName": "developer_name",
     *             "actionCode": 2,
     *             "actionValue": ["中国2"],
     *             "tableName": "dim_ycg_common_developer_m"
     *         }
     *     ]
     * }
     *
     * @param advanceSearchCustomerRequestDto
     * @return
     */
    private ArrayList<BaseTjFilterDto> assemTjFilters(AdvanceSearchCustomerRequestDto advanceSearchCustomerRequestDto, GetDeveloperFilterDataRequestDto getDeveloperFilterDataRequestDto) {
        if (advanceSearchCustomerRequestDto.getRelative() == null) {
            advanceSearchCustomerRequestDto.setRelative(1);
        }
        ArrayList<BaseTjFilterDto> baseTjFilterDtoList = new ArrayList<>();
        ArrayList<String> tagIds = new ArrayList<>();
        //获取数芯和开发商主数据相关的标签
        ArrayList<TagDto> tagDtoArrayList = developerService.getDeveloperTags();
        tagDtoArrayList.forEach(t -> {
            tagIds.add(t.getTag_id());
        });
        ArrayList<TagFilter> tagFilters = new ArrayList<>();
        int i = 0;
        for (FiltersDto filter : advanceSearchCustomerRequestDto.getFilters()) {
            if (filter.getActionValue() == null) {
                throw new BusinessLogicException("actionValue不允许为空");
            }
            BaseTjFilterDto baseTjFilterDto = new BaseTjFilterDto();
            if (i == 0) {
                baseTjFilterDto.setAssociate_previous(0);
            } else {
                //todo
                if (advanceSearchCustomerRequestDto.getRelative() == RELATIVE_AND) {
                    baseTjFilterDto.setAssociate_previous(1);
                } else if (advanceSearchCustomerRequestDto.getRelative() == RELATIVE_OR) {
                    baseTjFilterDto.setAssociate_previous(2);
                }
            }
            //特殊处理字段
            if (filter.getAttributeName().equals("x_cert_status")) {
                specialFieldHandleCertStatus(filter, baseTjFilterDto);
            } else if (filter.getAttributeName().equals("x_area")) {
                specialFieldHandleArea(filter, baseTjFilterDto);
            } else if (filter.getAttributeName().equals("x_purchase_area")) {
                specialFieldHandlePurchaseArea(filter, baseTjFilterDto);
            } else if (filter.getAttributeName().equals("land_usage")) {
                ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
                BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                subFilterDto.setTable_name(filter.getTableName());
                subFilterDto.setAttribute_name(filter.getAttributeName());
                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_CONTAIN);
                subFilterDto.setAssociate_previous(RELATIVE_NONE);
                if (filter.getActionValue().size() > 0) {
                    subFilterDto.setValue(filter.getActionValue().stream().collect(Collectors.joining(",")));
                } else {
                    subFilterDto.setValue("");
                }
                subFilterDtoList.add(subFilterDto);
                baseTjFilterDto.setSub_filter(subFilterDtoList);
            } else if(AdvanceSearchService.tagFields.containsKey(this.getTagFieldContainsKey(filter))) {
                //标签字段
                for(TagDto tagDto : tagDtoArrayList) {
                    //匹配到属于数芯标签
                    if (tagDto.getTag_name_en().equals(AdvanceSearchService.tagFields.get(this.getTagFieldContainsKey(filter)))) {
                        TagFilter tagFilter = new TagFilter();
                        tagFilter.setTag_id(tagDto.getTag_id());
                        ArrayList<String> tagValueList = (ArrayList<String>) MappingUtil.getSimpleMapperFacade().mapAsList(filter.getActionValue(), String.class);
                        tagFilter.setTag_value_id(tagValueList);
                        tagFilter.setAssociate_previous(advanceSearchCustomerRequestDto.getRelative());
                        if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_IN) || filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_EQ)) {
                            tagFilter.setOperate(BaseTjFilterDto.OPERATE_CONTAIN);
                        } else if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_NOT_IN_ALL)) {
                            tagFilter.setOperate(BaseTjFilterDto.OPERATE_NOT_CONTAIN);
                        }
                        tagFilters.add(tagFilter);
                    }
                }
                //不需要add baseTjFilterDto)
                i++;
                continue;
            } else {
                //常规字段
                //不需要子查询的场景，外层设置表和属性
                if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_EQ)
                        || Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NEQ)
                        || Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_IN)
                        || Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NOT_IN_ALL)
                        || Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_EXIST)
                        || Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NOT_EXIST)
                ) {
                    baseTjFilterDto.setTable_name(filter.getTableName());
                    baseTjFilterDto.setAttribute_name(filter.getAttributeName());
                }
                if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_EQ)) {
                    baseTjFilterDto.setOperate(BaseTjFilterDto.OPERATE_EQUAL);
                    baseTjFilterDto.setValue(filter.getActionValue().get(0));
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NEQ)) {
                    baseTjFilterDto.setOperate(BaseTjFilterDto.OPERATE_NOT_EQUAL);
                    baseTjFilterDto.setValue(filter.getActionValue().get(0));
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_IN)) {
                    baseTjFilterDto.setOperate(BaseTjFilterDto.OPERATE_CONTAIN);
                    baseTjFilterDto.setValue(Joiner.on(",").join(filter.getActionValue()));
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NOT_IN_ALL)) {
                    baseTjFilterDto.setOperate(BaseTjFilterDto.OPERATE_NOT_CONTAIN);
                    baseTjFilterDto.setValue(Joiner.on(",").join(filter.getActionValue()));
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_EXIST)) {
                    baseTjFilterDto.setOperate(BaseTjFilterDto.OPERATE_NOT_IS);
                    baseTjFilterDto.setValue(null);
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NOT_EXIST)) {
                    baseTjFilterDto.setOperate(BaseTjFilterDto.OPERATE_IS);
                    baseTjFilterDto.setValue(null);
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_NUMBER_RANGE)) {
                    //金额范围类、数值范围类 要用子查询
                    ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
                    for (int j = 0; j <= 1; j ++) {
                        BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                        subFilterDto.setTable_name(filter.getTableName());
                        subFilterDto.setAttribute_name(filter.getAttributeName());
                        subFilterDto.setValue(filter.getActionValue().get(j));
                        if (j == 0) {
                            subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LARGER_EQUAL);
                            subFilterDto.setAssociate_previous(RELATIVE_NONE);
                        } else {
                            subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LESS_EQUAL);
                            subFilterDto.setAssociate_previous(RELATIVE_AND);
                        }
                        subFilterDtoList.add(subFilterDto);
                    }
                    baseTjFilterDto.setSub_filter(subFilterDtoList);
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_DATE_RANGE)) {
                    //日期范围类，要用子查询
                    ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
                    for (int j = 0; j <= 1; j ++) {
                        BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                        subFilterDto.setTable_name(filter.getTableName());
                        subFilterDto.setAttribute_name(filter.getAttributeName());
                        subFilterDto.setValue(filter.getActionValue().get(j));
                        if (j == 0) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                Date dateStart = sdf.parse(filter.getActionValue().get(j));
                                LocalDate dateStartLocalDate = dateStart.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                LocalDateTime dateStartLocalDateTime = LocalDateTime.parse(dateStartLocalDate+"T"+"00"+":"+"00"+":00");
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                String dateStartLocalDateTimeString = dateTimeFormatter.format(dateStartLocalDateTime);
                                subFilterDto.setValue(dateStartLocalDateTimeString);
                                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LARGER_EQUAL);
                                subFilterDto.setAssociate_previous(RELATIVE_NONE);
                            } catch (Exception e) {
                                throw new BusinessLogicException("日期格式错误");
                            }
                        } else {
                            try {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                Date dateEnd = sdf.parse(filter.getActionValue().get(j));
                                LocalDate dateEndLocalDate = dateEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                                LocalDateTime dateEndLocalDateTime = LocalDateTime.parse(dateEndLocalDate+"T"+"23"+":"+"59"+":59");
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                String dateEndLocalDateTimeString = dateTimeFormatter.format(dateEndLocalDateTime);
                                subFilterDto.setValue(dateEndLocalDateTimeString);
                                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LESS_EQUAL);
                                subFilterDto.setAssociate_previous(RELATIVE_AND);
                            } catch (Exception e) {
                                throw new BusinessLogicException("日期格式错误");
                            }
                        }
                        subFilterDtoList.add(subFilterDto);
                    }
                    baseTjFilterDto.setSub_filter(subFilterDtoList);
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_TEXT_IN)) {
                    //文本包含任一
                    ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
                    for (int j = 0; j < filter.getActionValue().size(); j ++) {
                        BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                        subFilterDto.setTable_name(filter.getTableName());
                        subFilterDto.setAttribute_name(filter.getAttributeName());
                        subFilterDto.setValue(filter.getActionValue().get(j));
                        subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LIKE);
                        if (j == 0) {
                            subFilterDto.setAssociate_previous(RELATIVE_NONE);
                        } else {
                            subFilterDto.setAssociate_previous(RELATIVE_OR);
                        }
                        subFilterDtoList.add(subFilterDto);
                    }
                    baseTjFilterDto.setSub_filter(subFilterDtoList);
                } else if (Objects.equals(filter.getActionCode(), AdvanceSearchService.ACTIONCODE_TEXT_NOT_IN_ALL)) {
                    //文本不包含所有
                    ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
                    for (int j = 0; j < filter.getActionValue().size(); j ++) {
                        BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                        subFilterDto.setTable_name(filter.getTableName());
                        subFilterDto.setAttribute_name(filter.getAttributeName());
                        subFilterDto.setValue(filter.getActionValue().get(j));
                        subFilterDto.setOperate(BaseTjFilterDto.OPERATE_NOT_LIKE);
                        if (j == 0) {
                            subFilterDto.setAssociate_previous(RELATIVE_NONE);
                        } else {
                            subFilterDto.setAssociate_previous(RELATIVE_AND);
                        }
                        subFilterDtoList.add(subFilterDto);
                    }
                    baseTjFilterDto.setSub_filter(subFilterDtoList);
                }
            }
            baseTjFilterDtoList.add(baseTjFilterDto);

            i++;
        }
        if (advanceSearchCustomerRequestDto.getRelative() == RELATIVE_OR && baseTjFilterDtoList.size() == 0) {
            //任一模式下，如果没有普通字段参与筛选，则标签关联关系也是and
            if (tagFilters.size() > 0) {
                tagFilters.get(0).setAssociate_previous(RELATIVE_AND);
            }
        }
        if (baseTjFilterDtoList.size() > 0) {
            baseTjFilterDtoList.get(0).setAssociate_previous(RELATIVE_NONE);
        }
        getDeveloperFilterDataRequestDto.setTag_ids(tagIds);
        getDeveloperFilterDataRequestDto.setTag_filters(tagFilters);
        System.out.println("baseTjFilterDtoList================================" + baseTjFilterDtoList.toString());
        return baseTjFilterDtoList;
    }

    //特殊字段处理-证书状态
    private void specialFieldHandleCertStatus(FiltersDto filter, BaseTjFilterDto baseTjFilterDto) {
        //有效期内、已过期筛选，要用子查询
        baseTjFilterDto.setTable_name(null);
        baseTjFilterDto.setAttribute_name(null);
        //有效期内 now > start_date and now < end_date
        if (filter.getActionValue().get(0).equals("valid")) {
            ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
            BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
            subFilterDto.setTable_name(filter.getTableName());
            //发证日期
            subFilterDto.setAttribute_name("start_date");
            try {
                //有效期内、已过期筛选，要用子查询
                LocalDateTime localDateTime = LocalDateTime.now();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String localDateTimeString = dateTimeFormatter.format(localDateTime);
                subFilterDto.setValue(localDateTimeString);
                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LESS_EQUAL);
                subFilterDto.setAssociate_previous(RELATIVE_NONE);
            } catch (Exception e) {
                throw new BusinessLogicException("日期格式错误");
            }
            subFilterDtoList.add(subFilterDto);

            BaseTjFilterDto subFilterDto2 = new BaseTjFilterDto();
            subFilterDto2.setTable_name(filter.getTableName());
            //过期日期
            subFilterDto2.setAttribute_name("end_date");
            try {
                LocalDateTime localDateTime = LocalDateTime.now();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String localDateTimeString = dateTimeFormatter.format(localDateTime);
                subFilterDto2.setValue(localDateTimeString);
                //now < end_date
                subFilterDto2.setOperate(BaseTjFilterDto.OPERATE_LARGER);
                subFilterDto2.setAssociate_previous(RELATIVE_AND);
            } catch (Exception e) {
                throw new BusinessLogicException("日期格式错误");
            }
            subFilterDtoList.add(subFilterDto2);
            baseTjFilterDto.setSub_filter(subFilterDtoList);
        } else if (filter.getActionValue().get(0).equals("expire")) {
            //已过期  now > end_date
            ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
            BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
            subFilterDto.setTable_name(filter.getTableName());
            //过期日期
            subFilterDto.setAttribute_name("end_date");
            try {
                //有效期内、已过期筛选，要用子查询
                LocalDateTime localDateTime = LocalDateTime.now();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String localDateTimeString = dateTimeFormatter.format(localDateTime);
                subFilterDto.setValue(localDateTimeString);
                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_LESS_EQUAL);
                subFilterDto.setAssociate_previous(RELATIVE_NONE);
            } catch (Exception e) {
                throw new BusinessLogicException("日期格式错误");
            }
            subFilterDtoList.add(subFilterDto);
            baseTjFilterDto.setSub_filter(subFilterDtoList);
        }
    }


    //特殊字段处理-地区
    private void specialFieldHandleArea(FiltersDto filter, BaseTjFilterDto baseTjFilterDto) {
        //获取地区
        List<ProvinceAndCityDto> provinceAndCityDtoList = provinceAndCityService.getByCodes(filter.getActionValue());
        List<String> provinceCodes = new ArrayList<>();
        List<String> cityCodes = new ArrayList<>();
        for(ProvinceAndCityDto provinceAndCityDto : provinceAndCityDtoList) {
            if (provinceAndCityDto.getParentCode().equals("0")) {
                provinceCodes.add(provinceAndCityDto.getItemCode());
            } else {
                cityCodes.add(provinceAndCityDto.getItemCode());
            }
        }
        //省市都要查，则走子查询
        if (provinceCodes.size() != 0 && cityCodes.size() != 0) {
            //要用子查询
            baseTjFilterDto.setTable_name(null);
            baseTjFilterDto.setAttribute_name(null);

            ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
            BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
            subFilterDto.setTable_name(filter.getTableName());
            subFilterDto.setAssociate_previous(RELATIVE_NONE);
            //包含
            if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_IN)) {
                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_CONTAIN);
                subFilterDto.setAttribute_name("province_code");
                subFilterDto.setValue(Joiner.on(",").join(provinceCodes));
                subFilterDtoList.add(subFilterDto);

                BaseTjFilterDto subFilterDto2 = new BaseTjFilterDto();
                subFilterDto2.setTable_name(filter.getTableName());
                subFilterDto2.setOperate(BaseTjFilterDto.OPERATE_CONTAIN);
                subFilterDto2.setAttribute_name("city_code");
                subFilterDto2.setValue(Joiner.on(",").join(cityCodes));
                subFilterDto2.setAssociate_previous(RELATIVE_OR);
                subFilterDtoList.add(subFilterDto2);
            } else {
                //不包含
                subFilterDto.setOperate(BaseTjFilterDto.OPERATE_NOT_CONTAIN);
                subFilterDto.setAttribute_name("province_code");
                subFilterDto.setValue(Joiner.on(",").join(provinceCodes));
                subFilterDtoList.add(subFilterDto);

                BaseTjFilterDto subFilterDto2 = new BaseTjFilterDto();
                subFilterDto2.setTable_name(filter.getTableName());
                subFilterDto2.setOperate(BaseTjFilterDto.OPERATE_NOT_CONTAIN);
                subFilterDto2.setAttribute_name("city_code");
                subFilterDto2.setValue(Joiner.on(",").join(cityCodes));
                subFilterDto2.setAssociate_previous(RELATIVE_AND);
                subFilterDtoList.add(subFilterDto2);
            }

            baseTjFilterDto.setSub_filter(subFilterDtoList);
        } else {
            //不用子查询
            baseTjFilterDto.setTable_name(filter.getTableName());
            int operate = 0;
            if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_IN)) {
                operate = BaseTjFilterDto.OPERATE_CONTAIN;
            } else if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_NOT_IN_ALL)) {
                operate = BaseTjFilterDto.OPERATE_NOT_CONTAIN;
            }
            if (provinceCodes.size() != 0) {
                baseTjFilterDto.setAttribute_name("province_code");
                baseTjFilterDto.setOperate(operate);
                baseTjFilterDto.setValue(Joiner.on(",").join(provinceCodes));
            } else if (cityCodes.size() != 0) {
                baseTjFilterDto.setAttribute_name("city_code");
                baseTjFilterDto.setOperate(operate);
                baseTjFilterDto.setValue(Joiner.on(",").join(cityCodes));
            }
        }
    }


    //特殊字段处理-采购地区
    private void specialFieldHandlePurchaseArea(FiltersDto filter, BaseTjFilterDto baseTjFilterDto) {
        //获取地区
        List<ProvinceAndCityDto> provinceAndCityDtoList = provinceAndCityService.getByCodes(filter.getActionValue());
//        List<String> provinceCodes = new ArrayList<>();
        List<String> provinceNameList = new ArrayList<>();
        List<String> cityNameList = new ArrayList<>();
        for(ProvinceAndCityDto provinceAndCityDto : provinceAndCityDtoList) {
            if (provinceAndCityDto.getParentCode().equals("0")) {
                provinceNameList.add(provinceAndCityDto.getItemName());
            } else {
                cityNameList.add(provinceAndCityDto.getItemName());
            }
        }
        int operate = 0;
        int associatePrevious = 0;
        if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_IN)) {
            operate = BaseTjFilterDto.OPERATE_LIKE;
            associatePrevious = RELATIVE_OR;
        } else if (filter.getActionCode().equals(AdvanceSearchService.ACTIONCODE_NOT_IN_ALL)) {
            operate = BaseTjFilterDto.OPERATE_NOT_LIKE;
            associatePrevious = RELATIVE_AND;
        }
        ArrayList<BaseTjFilterDto> subFilterDtoList = new ArrayList<>();
        if (provinceNameList.size() != 0) {
            for (String s : provinceNameList) {
                BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                subFilterDto.setTable_name(filter.getTableName());
                subFilterDto.setAttribute_name("province_concat");
                subFilterDto.setValue(s);
                subFilterDto.setOperate(operate);
                subFilterDto.setAssociate_previous(associatePrevious);
                subFilterDtoList.add(subFilterDto);
            }
        }

        if (cityNameList.size() != 0) {
            for (String s : cityNameList) {
                BaseTjFilterDto subFilterDto = new BaseTjFilterDto();
                subFilterDto.setTable_name(filter.getTableName());
                subFilterDto.setAttribute_name("city_concat");
                subFilterDto.setValue(s);
                subFilterDto.setOperate(operate);
                subFilterDto.setAssociate_previous(associatePrevious);
                subFilterDtoList.add(subFilterDto);
            }
        }
        if (subFilterDtoList.size() >= 1) {
            subFilterDtoList.get(0).setAssociate_previous(0);
        }
        baseTjFilterDto.setSub_filter(subFilterDtoList);
    }

    public String getTagFieldContainsKey(FiltersDto filter) {
        return filter.getTableName() + "_" + filter.getAttributeName();
    }

}